<?php
include_once __DIR__."/db.class.php";

class Message
{
	/* public $flag = 1; */

	private $user_id;
	private $message;
	private $msg_to;
	private $now_time;

	function __construct($user_id, $message = "", $msg_to = 0)
	{
		$this -> user_id = $user_id;
		$this -> message = $message;
		$this -> msg_to = $msg_to;
		$this -> now_time = date("Y:m:d H:i:s");
	}

	public function send_message()
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("insert into messages (mes_content, user_id, mes_to) values(?, ?, ?);");
		/* $this -> flag = 1; */
		return $action -> execute(array($this -> message, $this -> user_id, $this -> msg_to));
	}

	public function get_msg_id($user_id)
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("select mes_id from users where user_id = ?");
		$action -> execute(array($user_id));
		$result = $action -> fetchAll();
		return $result[0]['mes_id'];
	}

	public function get_message($msg_id)
	{
		$connect = new Connect();
		$action	 = $connect -> connect_db() -> prepare("select messages.mes_id, messages.mes_content, messages.mes_pubdate, messages.mes_to, users.username from messages left join users on messages.user_id = users.user_id where (messages.mes_id > ?) and ((messages.mes_to = 0) or (messages.mes_to = ?)) order by messages.mes_id;");
		$action -> execute(array($msg_id, $this -> user_id));
		$result = $action -> fetchAll();
		if(count($result) === 0)
		{
			return false;
		}
		else
		{
			$action = $connect -> connect_db() -> prepare("update users set users.mes_id = ? where users.user_id = ?");
			$action -> execute(array($result[count($result) - 1]['mes_id'], $this -> user_id));
			return $result;
		}
	}
}
?>
